import jwt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication


# 继承BaseJSONWebTokenAuthentication，重写父类的authenticate方法
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = get_authorization_header(request).decode()
        if not jwt_value:
            raise AuthenticationFailed('Authorization 字段是必须的')
        try:
            jwt_value = jwt_value.split(' ')[1]
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('签名过期')
        except jwt.InvalidTokenError:
            print(jwt.InvalidTokenError)
            raise AuthenticationFailed('非法用户')
        except Exception as e:
            raise AuthenticationFailed(str(e))
        user = self.authenticate_credentials(payload)
        return user, jwt_value


